﻿Imports System.Text
Imports System.Security.Cryptography
Imports System.Runtime.CompilerServices
Imports System.Data.SqlClient
Imports System.IO
Imports System.IO.Compression
Imports System.Net
Imports System.Xml
Imports IWshRuntimeLibrary

Public Class LoginForm1

    ' TODO: Insert code to perform custom authentication using the provided username and password 
    ' (See http://go.microsoft.com/fwlink/?LinkId=35339).  
    ' The custom principal can then be attached to the current thread's principal as follows: 
    '     My.User.CurrentPrincipal = CustomPrincipal
    ' where CustomPrincipal is the IPrincipal implementation used to perform authentication. 
    ' Subsequently, My.User will return identity information encapsulated in the CustomPrincipal object
    ' such as the username, display name, etc.

    Private Sub OK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OK.Click
        My.Settings.USU_ID = 0
        My.Settings.USU_NOME = UsernameTextBox.Text.Replace("@misasi.com.br", "") & "@misasi.com.br"
        My.Settings.USU_SENHA = PasswordTextBox.Text
        My.Settings.Save()
        Dim log = ExecuteSQL("EXEC psLoginIntranet '" & My.Settings.USU_NOME & "', '" & My.Settings.USU_SENHA.AcertaSenha & "'")
        If log.HasRows Then
            log.Read()
            My.Settings.USU_ID = log("USU_ID")
            My.Settings.Save()
            log.Dispose()
            If My.Application.CommandLineArgs.Count > 0 Then
                procedimento()
            End If
        Else
            MsgBox("Erro!, verifique seu login e senha")
        End If

        Application.Exit()
    End Sub

    Private Sub LoginForm1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        UsernameTextBox.Text = My.Settings.USU_NOME
        PasswordTextBox.Text = My.Settings.USU_SENHA
        Try
            For Each arq In Directory.GetFiles(Path.GetTempPath)
                Try
                    System.IO.File.Delete(arq)
                Catch ex As Exception
                End Try
            Next
        Catch ex As Exception

        End Try

        If Application.ExecutablePath().Replace("\ARQUIVOS DA INTRANET.EXE", "") = Environment.GetFolderPath(Environment.SpecialFolder.SendTo) Then
            If My.Settings.USU_ID > 0 Then
                procedimento()
                Application.Exit()
            Else
                Me.Show()
            End If
        Else
            Try
                My.Settings.USU_ID = 0
                FileCopy(Application.ExecutablePath(), Environment.GetFolderPath(Environment.SpecialFolder.SendTo) & "\ARQUIVOS DA INTRANET.EXE")
                MsgBox("Aplicativo instalado com sucesso!", MsgBoxStyle.Information, "INTRANET MISASI")
                My.Settings.Save()
                Application.Exit()
            Catch ex As Exception
                MsgBox(ex.Message, MsgBoxStyle.Critical, "INTRANET MISASI")
                My.Settings.USU_ID = 0
                My.Settings.Save()
                Application.Exit()
            End Try

        End If

    End Sub

    Private Sub procedimento()
        Try
            If My.Application.CommandLineArgs(0).EndsWith("--logoff") Then
                If MsgBox("Deseja realmente fazer logoff do aplicativo 'ARQUIVOS DA INTRANET'?" & vbNewLine & "Você não podera enviar arquivos enquanto não se logar novamente!", MsgBoxStyle.YesNo, "ARQUIVOS DA INTRANET") = MsgBoxResult.Yes Then
                    My.Settings.USU_ID = 0
                    My.Settings.Save()
                    MsgBox("Logoff realizado com sucesso!", MsgBoxStyle.Exclamation, "INTRANET MISASI")
                End If
                Application.Exit()
            End If
            criatalho()
            Me.Hide()
            Dim thename = ""
            If My.Application.CommandLineArgs.Count = 1 Then thename = Path.GetFileName(My.Application.CommandLineArgs(0))
            Dim DESC = PerguntaNomeArquivo(thename)
            If String.IsNullOrWhiteSpace(DESC) = True Then
                Application.Exit()
            Else
                'colocar aqui o esquema de CLI_ID
                Dim pub As Integer = 0
                If MsgBox("Este arquivo é público?", MsgBoxStyle.YesNo) = MsgBoxResult.Yes Then
                    pub = 1
                Else
                    pub = 0
                End If
                Dim TEMPZIP = Path.GetTempPath & "\" & DESC.Replace(" ", "_").ToLower & ".zip"
                Dim bitly As String = ArquivoNaoExiste(DESC.Replace(" ", "_").ToLower & ".zip")
                If bitly = "EXISTE" Then
                    MsgBox("Esse arquivo já existe! Escolha outro nome.", MsgBoxStyle.Exclamation, "Erro")
                    Me.Close()
                Else
                    Dim dir = Path.GetTempPath & "/TEMPFILES/"

                    If Directory.Exists(dir) = True Then
                        Directory.Delete(dir, True)
                    End If
                    Directory.CreateDirectory(dir)
                    _notifyicon.ShowBalloonTip(100000, "COPIANDO ARQUIVOS", "AGUARDE ALGUNS MINUTOS", ToolTipIcon.Info)
                    For Each arqq In My.Application.CommandLineArgs
                        If System.IO.File.GetAttributes(arqq) = FileAttributes.Directory Then
                            Dim curfile As New DirectoryInfo(arqq)
                            My.Computer.FileSystem.CopyDirectory(arqq, dir & "/" & curfile.Name)
                            _notifyicon.ShowBalloonTip(100000, "COPIANDO DIRETORIO", curfile.Name, ToolTipIcon.Info)
                        Else
                            Dim curfile As New FileInfo(arqq)
                            System.IO.File.Copy(arqq, dir & "/" & curfile.Name)
                            _notifyicon.ShowBalloonTip(100000, "COPIANDO ARQUIVO", curfile.Name, ToolTipIcon.Info)
                        End If

                    Next
                    _notifyicon.ShowBalloonTip(100000, "CRIANDO ZIP", TEMPZIP, ToolTipIcon.Info)

                    ZipFile.CreateFromDirectory(dir, TEMPZIP, CompressionLevel.Optimal, False)
                    _notifyicon.ShowBalloonTip(100000, "PREPARANDO UPLOAD", TEMPZIP, ToolTipIcon.Info)



                    Dim _FileInfo As New System.IO.FileInfo(TEMPZIP)
                    Try
                        ' Create FtpWebRequest object from the Uri provided
                        Dim _FtpWebRequest = CType(FtpWebRequest.Create(New Uri("ftp://186.202.124.13/Web/intranet/upload/arquivos/" & "/" & _FileInfo.Name)), System.Net.FtpWebRequest)


                        ' Provide the WebPermission Credintials
                        _FtpWebRequest.Credentials = New System.Net.NetworkCredential("misasi", "d3m7k8")

                        ' By default KeepAlive is true, where the control connection is not closed
                        ' after a command is executed.
                        _FtpWebRequest.KeepAlive = True

                        ' set timeout for 20 seconds
                        _FtpWebRequest.Timeout = 180000

                        ' Specify the command to be executed.
                        _FtpWebRequest.Method = System.Net.WebRequestMethods.Ftp.UploadFile

                        ' Specify the data transfer type.
                        _FtpWebRequest.UseBinary = False
                        _FtpWebRequest.UsePassive = True

                        ' Notify the server about the size of the uploaded file
                        _FtpWebRequest.ContentLength = _FileInfo.Length
                        Dim TOTAL = _FtpWebRequest.ContentLength
                        ' The buffer size is set to 2kb
                        Dim buffLength As Integer = 204800
                        Dim buff(buffLength - 1) As Byte

                        ' Opens a file stream (System.IO.FileStream) to read the file to be uploaded
                        Dim _FileStream As System.IO.FileStream = _FileInfo.OpenRead()

                        ' Stream to which the file to be upload is written
                        Dim _Stream As System.IO.Stream = _FtpWebRequest.GetRequestStream()

                        ' Read from the file stream 2kb at a time
                        Dim contentLen As Integer = _FileStream.Read(buff, 0, buffLength)
                        Dim parcial As Integer = 0
                        Dim controle As Integer = 0
                        ' Till Stream content ends
                        Do While contentLen <> 0
                            ' Write Content from the file stream to the FTP Upload Stream
                            _Stream.Write(buff, 0, contentLen)
                            Dim porcentagem As Integer = (parcial / TOTAL * 100)
                            If porcentagem Mod 2 = 0 And porcentagem = controle Then
                                controle = controle + 2
                                _notifyicon.ShowBalloonTip(10000, "PROGRESSO", porcentagem & "%", ToolTipIcon.Info)
                            End If
                            _notifyicon.Text = "FAZENDO UPLOAD... " & porcentagem & "%"
                            contentLen = _FileStream.Read(buff, 0, buffLength)
                            parcial = parcial + buffLength
                            Me.Update()
                        Loop
                        Me.Hide()
                        ' Close the file stream and the Request Stream
                        _Stream.Close()
                        _Stream.Dispose()
                        _FileStream.Close()
                        _FileStream.Dispose()
                        ExecuteSQL("INSERT INTO intranet_Arquivos (ARQ_ARQUIVO, ARQ_LINK, ARQ_DESCRICAO, USU_ID, ARQ_PUBLICO) values ('" & DESC & "', '" & bitly & "', '" & DESC & "', '" & Convert.ToInt16(My.Settings.USU_ID) & "', " & pub & ")")
                        Clipboard.SetText(bitly)
                        If MsgBox("Upload realizado com sucesso!" & vbNewLine & "Link copiado: " & bitly & vbNewLine & vbNewLine & "Deseja abrir a intranet agora?", MsgBoxStyle.YesNo, "INTRANET MISASI") = MsgBoxResult.Yes Then Process.Start("http://misasi.com.br/intranet/arquivos")

                    Catch ex As Exception
                        _notifyicon.ShowBalloonTip(10000, "Erro no Upload", ex.Message, ToolTipIcon.Error)
                    End Try

                    Directory.Delete(dir, True)
                    System.IO.File.Delete(TEMPZIP)


                End If
            End If
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, ex.Source)
            Application.Exit()
        End Try
    End Sub

    Private Sub UsernameTextBox_TextChanged(sender As Object, e As EventArgs) Handles UsernameTextBox.LostFocus
        sender.text = sender.text.replace("@misasi.com.br", "") & "@misasi.com.br"
    End Sub
End Class

Public Module SQL

    Private Function OpenConnection()
        Dim Connection = New SqlConnection(My.Settings.Conexao)
        If Not Connection.State = ConnectionState.Open Then
            Connection.Open()
        End If
        Return Connection
    End Function

    Function ExecuteSQL(SQLQuery As String) As SqlDataReader
        Dim DataSet As New SqlCommand(SQLQuery, OpenConnection())
        Dim tabela As SqlDataReader
        DataSet.CommandTimeout = 99999
        tabela = DataSet.ExecuteReader()
        Return tabela
    End Function
End Module

Public Module MD



    Public Function PerguntaNomeArquivo(Nome As String) As String

        Dim myValue As String

        myValue = InputBox("Digite a descrição do arquivo:", "INTRANET MISASI", Nome)
        ' If user has clicked Cancel, set myValue to defaultValue
        Return myValue
    End Function



    Public Function ArquivoNaoExiste(Arquivo As String) As String
        Dim XML As String = "http://api.bit.ly/v3/shorten?login=socialflagshipag&apiKey=R_66702ca40fbd40c9b7ee27d6022aec3a&uri=http://misasi.com.br/intranet/upload/arquivos/" & Arquivo & "&format=xml"
        Dim Client As New WebClient
        Dim resposta As String = Client.DownloadString(XML)

        Dim respurl() As String = resposta.Split(New String(0) {"<url>"}, StringSplitOptions.None)
        respurl = respurl
        respurl = respurl(1).Split(New String(0) {"</url>"}, StringSplitOptions.None)
        resposta = respurl(0).Trim
        Dim arq As SqlDataReader = ExecuteSQL("EXEC psVerificaArquivo '" & resposta & "'")
        arq.Read()
        If arq("STATUS").ToString = 0 Then
            Return "EXISTE"
        Else
            Return resposta
        End If

    End Function

    <Extension()>
    Public Function AcertaSenha(_senha As String) As String

        Dim senha = New StringBuilder()

        Dim md5s = MD5.Create()
        Dim entrada As Byte() = Encoding.ASCII.GetBytes(_senha)
        Dim hash As Byte() = md5s.ComputeHash(entrada)
        Dim sb = New StringBuilder()
        For i = 0 To hash.Length - 1
            senha.Append(hash(i).ToString("X2"))
        Next
        Return senha.ToString().ToLower()
    End Function

    Public Sub criatalho()
        Dim WshShell As New WshShell
        ' short cut files have a .lnk extension
        Dim atalho As IWshRuntimeLibrary.IWshShortcut = DirectCast(WshShell.CreateShortcut(Environment.GetFolderPath(Environment.SpecialFolder.StartMenu) & "\Fazer logoff de ARQUIVOS.lnk"), IWshRuntimeLibrary.IWshShortcut)

        ' set the shortcut properties
        With atalho
            .TargetPath = Application.ExecutablePath
            .WindowStyle = 1I
            .Description = "Fazer logoff do aplicativo 'arquivos da intranet'"
            .WorkingDirectory = Application.StartupPath
            ' the next line gets the first Icon from the executing program
            .IconLocation = Application.ExecutablePath & ", 0"
            .Arguments = "--logoff"
            .Save() ' save the shortcut file
        End With

    End Sub
End Module
